package giftmail.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import giftmail.util.AppForWxGetPrePayIdUtil;
import giftmail.util.DateUtils;
import giftmail.util.GetWxOrderNo;
import giftmail.util.RequestHandler;
import giftmail.util.SGErrorCode;
import giftmail.util.TenpayUtil;

@Controller
@RequestMapping(value = "/wxController")
public class WxPayController {

	/**
	 * 微信支付-获取预支付id
	 * 
	 * @author Demo
	 */
	@ResponseBody
	@RequestMapping("/getPrePayId")
	public String getPrePayId(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		// 调用微信URL
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		// Wx参数--商品描述
		String body = request.getParameter("body");
		// 订单号
		String outTradeNo = request.getParameter("outTradeNo");
		// 价格
		String totalFee = request.getParameter("totalFee");
		// 調用時間
		String currTime = TenpayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		String strReq = strTime + strRandom;
		// Wx参数--附加数据(非必选)
		String attach = request.getParameter("attach");
		attach = "{" + "type=reservePay" + "&" + "orderId=" + outTradeNo + "&" + "creatime=" + currTime + "}";
		// Wx参数--应用ID
		String appid = "xxx";
		// Wx参数--商户号
		String mch_id = "xxx";
		// API密钥，在商户平台设置
		String partnerkey = "xxx";
		String appsecret = "xxx";
		// Wx参数--随机字符串
		String nonce_str = strReq;

		float sessionmoney = Float.parseFloat(totalFee);
		if (sessionmoney <= 0) {
			sessionmoney = 0.01f;
		}
		String finalmoney = String.format("%.2f", sessionmoney);
		finalmoney = finalmoney.replace(".", "");
		
		// Wx参数--总金额
		int intMoney = Integer.parseInt(finalmoney);

		// 提交到微信支付的随机订单号，避免支付失败后相同订单号无法调起微信支付(原订单号加4位随机数)
		// Wx参数--商户订单号
		String out_trade_no = outTradeNo + TenpayUtil.buildRandom(4);

		// Wx参数--终端IP
		String spbill_create_ip = request.getRemoteAddr();
		// Wx参数--回调通知地址
		String notify_url = "http://xxx:xx77/notify_url.jsp";
		
		// Wx参数--交易类型
		String trade_type = "APP";
		
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("attach", attach);
		packageParams.put("body", body);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("notify_url", notify_url);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("total_fee", intMoney + "");
		packageParams.put("trade_type", trade_type);
		
		Date time_start=new Date();
		Date time_expire=DateUtils.add(DateUtils.add(time_start, 12, 5), 13, 1);
		// Wx参数--交易起始时间
		packageParams.put("time_start", sdf.format(time_start));
		// Wx参数--交易结束时间
		packageParams.put("time_expire", sdf.format(time_expire));
		
		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init(appid, appsecret, partnerkey);
		// Wx参数--签名
		String sign = reqHandler.createSign(packageParams);
		
		String xml = "<xml>" + "<appid>" + appid + "</appid>" 
				+ "<attach>" + attach + "</attach>" 
				+ "<body><![CDATA[" + body + "]]></body>" + "<mch_id>" + mch_id + "</mch_id>" 
				+ "<nonce_str>" + nonce_str + "</nonce_str>" 
				+ "<notify_url>" + notify_url + "</notify_url>" 
				+ "<out_trade_no>" + out_trade_no + "</out_trade_no>"
				+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 
				+ "<total_fee>" + intMoney + "</total_fee>" 
				+ "<trade_type>" + trade_type + "</trade_type>" 
				+ "<time_start>"+sdf.format(time_start)+"</time_start>" 
				+ "<time_expire>"+sdf.format(time_expire)+"</time_expire>"
				+ "<sign>" + sign + "</sign>" + "</xml>";

		String prepay_id = "";
		try {
			//httpClient向微信发送参数
			prepay_id = new GetWxOrderNo().getPayNo(createOrderURL, xml);
			if (prepay_id.equals("")) {
				//return new MessageEntity(-1,"操作失败").toJson();
				return SGErrorCode.RES_PARAMS_ERROR.toString();

			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return new AppForWxGetPrePayIdUtil(0, "操作成功", prepay_id,sign,nonce_str).toJson();
	}
}
